/* © 2007 Adobe Systems Incorporated. All rights reserved. */
package com.shubhjai.musiclib.commands
{
	import flash.data.SQLStatement;
	import flash.events.ErrorEvent;
	import flash.data.SQLConnection;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import com.shubhjai.musiclib.managers.DatabaseConnectionManager;
	import flash.errors.SQLError;


	/**
	 * This is an abstract command that standardizes takes care of some SQL 
	 * related housekeeping.
	 * 
	 * Subclasses should implement the executeSQL() method, which will be invoked
	 * after the connection is properly initialized.
	 */ 
	public class SQLCommand extends Command
	{
		protected var conn : SQLConnection;
		protected var stmt : SQLStatement;
		
		/**
		 * Constructor
		 */ 
		public function SQLCommand() : void
		{
		}
		
		
			/**
		 * Execute the command. Subclasses should not override this method, but instead override executeSQL.
		 */ 
		override public function execute() : void
		{
			conn = DatabaseConnectionManager.getInstance().getConnection( onConnOpen );
			stmt = new SQLStatement();
			stmt.sqlConnection = conn;
			
			
			// for the M4 AIR runtime, we share a single SQLConnection to avoid pending issues
			if ( conn.connected )
			{
				executeSQL();
			}
			
			//conn.addEventListener( SQLErrorEvent.ERROR, onSQLConnError );
		}	
		
		/**
		 * Start executing the actual SQL. This will automatically get invoked after the connection is opened.
		 */ 
		protected function executeSQL() : void
		{
			throw new Error( "SQLCommand: Subclasses must override executeSQL.");
		}
		
		
		/**
		 * This function can be passed to responders for a default error callback. 
		 */ 
		protected function onSQLError( err:SQLError ) : void
		{
			notifyError( "Error executing SQL: " + err.message + " : " + err.errorID);
		}
		
	
		private function onConnOpen( evt:SQLEvent ) : void
		{
			logDebug("onConnOpen()");
			executeSQL();
		}
		
		/**
		 * 
		 */ 	
		override protected function notifyComplete():void
		{
			closeSQLConnection();
			super.notifyComplete();
		}
		
		override protected function notifyError( msg:String ) : void
		{
			closeSQLConnection();
			super.notifyError(msg);
		}
		

		
		/**
		 * Cleanup the SQL connection.
		 */ 
		protected function closeSQLConnection() : void
		{
			if ( conn )	
			{
				//conn.removeEventListener( SQLErrorEvent.ERROR, onSQLConnError );
				conn.removeEventListener( SQLEvent.OPEN, onConnOpen );
				conn = null;
			}
			if ( stmt && stmt.prepared )
			{
				stmt.reset();  
				stmt.sqlConnection = null;
				stmt = null;
			}
			
			
		}

	}
}